/**
 * 企业微信工具函数
 */

// 检测是否在企业微信环境中
export function isWeComEnvironment(): boolean {
    const userAgent = navigator.userAgent.toLowerCase()
    return userAgent.includes('wxwork') || userAgent.includes('enterprise')
}

// 获取企业微信企业ID
export function getWeComCorpId(): Promise<string> {
    return new Promise((resolve, reject) => {
        if (!isWeComEnvironment()) {
            reject(new Error('不在企业微信环境中'))
            return
        }

        // 检查是否已加载企业微信JS-SDK
        if (typeof window.wx === 'undefined') {
            // 动态加载企业微信JS-SDK
            loadWeComJSSDK().then(() => {
                getCorpIdFromSDK(resolve, reject)
            }).catch(reject)
        } else {
            getCorpIdFromSDK(resolve, reject)
        }
    })
}

// 动态加载企业微信JS-SDK
function loadWeComJSSDK(): Promise<void> {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = 'https://res.wx.qq.com/wwopen/js/jsapi/jweixin-1.0.0.js'
        script.onload = () => resolve()
        script.onerror = () => reject(new Error('企业微信JS-SDK加载失败'))
        document.head.appendChild(script)
    })
}

// 从SDK获取企业ID
function getCorpIdFromSDK(resolve: (corpId: string) => void, reject: (error: Error) => void) {
    try {
        // 企业微信环境下获取企业信息
        window.wx.ready(() => {
            window.wx.invoke('getContext', {}, (res: any) => {
                if (res.err_msg === 'getContext:ok') {
                    const corpId = res.entry?.corpid || res.corpid
                    if (corpId) {
                        resolve(corpId)
                    } else {
                        reject(new Error('无法获取企业ID'))
                    }
                } else {
                    reject(new Error('获取企业信息失败: ' + res.err_msg))
                }
            })
        })

        window.wx.error((res: any) => {
            reject(new Error('企业微信SDK初始化失败: ' + res.errMsg))
        })

        // 配置企业微信SDK（这里需要根据实际情况配置）
        window.wx.config({
            beta: true,
            debug: false,
            appId: '', // 企业的CorpID
            timestamp: Math.floor(Date.now() / 1000),
            nonceStr: Math.random().toString(36).substr(2, 15),
            signature: '', // 这里需要从后端获取签名
            jsApiList: ['getContext']
        })
    } catch (error) {
        reject(new Error('获取企业ID过程中发生错误: ' + (error instanceof Error ? error.message : String(error))))
    }
}

// 从URL参数中获取企业ID（备用方案）
export function getCorpIdFromUrl(): string | null {
    const urlParams = new URLSearchParams(window.location.search)
    return urlParams.get('corpid') || urlParams.get('corp_id')
}

// 获取企业微信用户信息
export function getWeComUserInfo(): Promise<any> {
    return new Promise((resolve, reject) => {
        if (!isWeComEnvironment()) {
            reject(new Error('不在企业微信环境中'))
            return
        }

        window.wx.ready(() => {
            window.wx.invoke('getUserInfo', {}, (res: any) => {
                if (res.err_msg === 'getUserInfo:ok') {
                    resolve(res)
                } else {
                    reject(new Error('获取用户信息失败: ' + res.err_msg))
                }
            })
        })
    })
}

// 扩展Window接口以支持企业微信wx对象
declare global {
    interface Window {
        wx: any
    }
} 